import { createChunk } from '/createChunk.js'

const CHUNK_SIZE = 1024 * 1024 * 5
const THREAD_COUNT = navigator.hardareConcurrency || 4


export function cutFile(file) {
    return new Promise((resolve)=>{
        let result = []
        const chunkCount = Math.ceil(file.size / CHUNK_SIZE)
        const workerChunkCount = Math.ceil(chunkCount / THREAD_COUNT)
        let finishCount = 0
        for (let i = 0;i < THREAD_COUNT; i++) {
            const worker = new Worker('./worker.js', {
                type: 'module'
            })
            let startIndex = i * workerChunkCount //起始的分片下标
            let endIndex = Math.min((i + 1) * workerChunkCount, chunkCount)
            worker.postMessage({
                file,
                CHUNK_SIZE,
                startIndex,
                endIndex
            })
            worker.onmessage = (e) =>{
                // for(let i = startIndex; i < endIndex; i++) {
                //     result[i] = e.data[i - startIndex]
                // }
                worker.terminate()
                result[i] = e.data
                finishCount++
                if(finishCount === THREAD_COUNT){
                    resolve(result.flat())
                }
            }
        }
    })
}